<?php

// 平台
class TaskAction extends Action {
	
	private $cLogs = null;
	private $cTask 	= null;
	private $cUsers = null;
	private $cPlantform = null;
	private $cAdmin		= null;
	private $cOrder		= null;
	private $cTaskLog	= null;
	private $cShipping	= null;
	
	function __construct(){

		//判断管理员登录状态
		admin_login_check();
		
		import('@.ORG.Get');
		import('@.ORG.Post');
		import('@.ORG.Task');
		import('@.ORG.Users');
		import('@.ORG.Plantform');
		import('@.ORG.Admin');
    	import('@.ORG.Order');
    	import('@.ORG.TaskLog');
    	import('@.ORG.Shipping');
    	import('@.ORG.Logs');
    	
		$this->cUsers 	= new Users();
		$this->cTask 	= new Task();
		$this->cPlantform 	= new Plantform();
		$this->cAdmin 		= new Admin();
		$this->cOrder 		= new Order();
		$this->cTaskLog		= new TaskLog();
		$this->cShipping	= new Shipping();
		$this->cLogs		= new Logs();
	}

    /**
     * 列表
     */
    public function index(){

    	admin_role('Task:index');

        $get = get(
    		array(
	    		array('begin_time'			,''	,short_date(strtotime('-1 days'))),
	    		array('end_time'			,''	,short_date()),
	    		array('plantform_id'		,'intval'	,0),
	    		array('user_id'				,'intval'	,0),
    				
    			array('pay_status_id'				,'intval'	,-99),
    			array('task_status_id'				,'intval'	,-99)
    		)
    	);
    	

    	$where = $get;
    	
    	//判断是否是运维
		if($this->cAdmin->is_group_code('business_man')){
			//是运维，只能看到自己的任务
			$where['business_admin_id'] = admin_id_get();
		}
		
		//判断是否是运维
		else if($this->cAdmin->is_group_code('operator')){
			//是运维，只能看到自己的任务
			$where['order_admin_id'] = admin_id_get();
		}
		
		$pay_status_id		= $get['pay_status_id'];
		$task_status_id		= $get['task_status_id'];
		
		if($pay_status_id != -99){
			//支付状态
			$where['pay_status'] = $pay_status_id;
		}

		//任务状态
		$where['task_status'] = $task_status_id;
		
    	$plantform_id	= $get['plantform_id'];
    	$user_id		= $get['user_id'];
    	
 
    	
    	//平台
    	$plantforms = $this->cPlantform->lists();
    	
    	//任务
    	$tasks = $this->cTask->lists($where);

    	//汇总信息
    	$summary = $this->cTask->summary($where);
    	
    	//客户列表
    	$users = $this->cUsers->my_users();
    	
    	//开始时间
    	$begin_time	= $get['begin_time'];
    	//结束时间
    	$end_time	= $get['end_time'];
    	
    	//汇总查看权限
    	$task_summary_has_role = has_role('Task:summary');
    	
    	
    	//订单状态
    	$task_status = C('TASK_STATUS');
    	
    	//支付状态
    	$task_pay_status = C('TASK_PAY_STATUS');
    	
    	
    	$this->assign(
    		array(
    			'APP_NAME'		=> APP_NAME,
    			'tasks'			=> $tasks,
    			'users'			=> $users,
    			'begin_time'	=>	$begin_time,
    			'end_time'		=> $end_time,
    			'plantforms'	=> $plantforms,
    			'plantform_id'	=> $plantform_id,
    			'user_id'		=> $user_id,
    			'summary'		=> $summary,
    			'task_summary_has_role' => $task_summary_has_role,
    			'task_pay_status'	=> $task_pay_status,
    			'task_status'		=> $task_status,
    			'pay_status_id'		=> $pay_status_id,
    			'task_status_id'	=> $task_status_id,   				
    				
    			'MainPage'		=> 'Task:index'
    		)
    	);
    	$this->display(C('ADM_TEMPLATE'));
    }
    
    public function add(){

    	admin_role('Task:add');
    	    	
    	$post = post(array(
    		array('user_id'				,'intval',0),
    		array('begin_time'			,'trim',''),
    		array('end_time'			,'trim','')
    	));
    	
    	$user_id		= $post['user_id'];   	
    	
		import('@.ORG.FileCsvUpload');
		import('@.ORG.TaskOrdersCsv');
		
		//代付费
		$task_order_money 	= 0;
		//订单量
		$order_count		= 0;
		
		//上传csv
		$up_success	= 0;
		$up_error	= '';
		
		//数据
		$task_orders = array();
		
    	$cfcUP = new FileCsvUpload('task_orders');
    	$up_result = $cfcUP->upload();
		    	
    	if(is_null($up_result)){
    		//不是上传
    	}else if($up_result == false){
    		//上传错误
    		$up_error = $cfcUP->file_error();
    	}else{
    		$up_success	= 1;
    		
    		$cfcUP->remove_header();
    		$file_data = $cfcUP->file_data();
    		
    		//转换
    		$cToCsv = new TaskOrdersCsv();
    		$task_orders = $cToCsv->array_to_data($file_data);
    		
    		//汇总
    		$sum = $cToCsv->summary($task_orders);
    		
    		//代付费
			$task_order_money 	= $sum['task_order_money'];
			//订单量
			$order_count		= $sum['order_count'];
    	}

    	//客户列表
    	$users = $this->cUsers->my_users();

    	//平台
    	$plantforms = $this->cPlantform->lists();
    	
    	//订单状态
    	$task_status = C('TASK_STATUS');
    	
    	//支付状态
    	$task_pay_status = C('TASK_PAY_STATUS');

    	//开始结束时间
    	if($post['begin_time'] != ''){
    		$begin_time = $post['begin_time'];
    	}else{
    		$begin_time = full_date();
    	}

    	if($post['end_time'] != ''){
    		$end_time = $post['end_time'];
    	}else{
    		$end_time 	= (strtotime(short_date()) + 86400 - 1);
    		$end_time 	= full_date($end_time);
    	}

    	//序列化的订单
    	$serialize_orders = serialize($task_orders);
    	    	
    	$this->assign(
    		array(
    			'APP_NAME'			=> APP_NAME,
    			'plantforms'		=> $plantforms,
    			'users'				=> $users,
    			'task_status'		=>$task_status,
    			'task_pay_status'	=>$task_pay_status,
    			'begin_time'		=> $begin_time,
    			'end_time'			=> $end_time,
    			'task_orders'		=> $task_orders,
    			'serialize_orders'	=> $serialize_orders,
    			'task_order_money' 	=> $task_order_money,
    			'order_count' 		=> $order_count,
    			'file_error'		=> $file_error,    		
    			'up_success'		=> $up_success,
    			'user_id'			=> $user_id,
    			'MainPage'			=> 'Task:add'
    		)
    	);
    	$this->display(C('ADM_TEMPLATE'));
    }
    
    public function add_do(){
    	
    	admin_role('Task:add');
    	
    	import('@.ORG.TaskOrdersCsv');
    	import('@.ORG.OrderGoods');
    	
   		$post = post(array(
    		array('user_id'				,'intval',''),
    		array('activity'			,'trim',''),
    		array('remark'				,'trim',''),
    		array('order_count'			,'intval',''),
    		array('task_order_money'	,'floatval',''),
    		array('commission_money'	,'floatval',''),
    		array('value_added_money'	,'floatval',''),
   			array('pay_status'			,'intval',0),
   			array('task_status'			,'intval',0),
    		array('begin_time'			,'',''),
    		array('end_time'			,'',''),
    		array('serialize_orders'	,'',''),
    	));

    	//任务csv
    	$cToCsv = new TaskOrdersCsv();
    	$task_orders = $cToCsv->unserialize($post['serialize_orders']);
    	
    	//去掉订单
    	unset($post['serialize_orders']);
    	$business_admin_id = admin_id_ajax();
    	
    	if($business_admin_id == 0){
    		json_error('登录状态失效,请重新登录');
    	}
    	
    	$post['business_admin_id'] = $business_admin_id;
    	
    	//选检查订单是否为空,为空，不得添加，需要修改
    	$summary = array();
    	if(empty($task_orders)){
    		json_error('没有订单数据，请先上传');
    	}
    	$summary = array();
    	
    	//添加任务单
    	$add_result = $this->cTask->add($post);
    		
		if($add_result){

			//添加订单
			$task_id = $add_result;
			
			//添加订单数量
			$order_add_count = 0;
			//添加商品数量
			$goods_add_count = 0;
			
    		foreach ($task_orders as $i => $o){
    			//添加入库
    			    			
    			$order = array(
    				'task_id' => $task_id,
    				
    				'shipping_id' 	=> $o['shipping_id'],
		            'invoice_no' 	=> $o['invoice_no'],
		            'consignee' 	=> $o['consignee'],
		            'address' 		=> $o['address'],
		            'mobile_phone'	=> $o['mobile_phone'],
		            'keywords' 		=> $o['keywords'],
		            'goods_amount' 	=> $o['goods_price'],
		            'comment' 		=> $o['comment']
    			);
    			
    			//添加订单
    			$order_id = $this->cOrder->add($order);
    			
    			if($order_id > 0){
    				$order_add_count++;
    				//订单添加成功
    				$ogData = array(
						'order_id' 		=> $order_id,
			            'goods_url' 	=> $o['goods_url'],
                        'goods_id' 	    => item_id($o['goods_url']),
                        'goods_name' 	=> $o['goods_name'],
			            'goods_number' 	=> $o['goods_number'],
			            'goods_price' 	=> $o['goods_price'],
			            'final_price' 	=> $o['final_price']
    				);
    				
    				//订单商品添加成功
    				$cOG = new OrderGoods();
    				$og_id = $cOG->add($ogData);
    				
    				if($og_id > 0){
    					$goods_add_count++;
    				}
    			}
    		}
    		
    		if($order_add_count > 0){
    			
    			$this->cLogs->add('Task:add','添加任务单成功:'.$task_id);
    			
		    	json_success('成功添加订单'.$order_add_count.'个');
		    }else{
		    	json_error('添加订单失败');
		    }

		}else{
			json_error('任务添加失败');
		}
    }
    
    //详情或修改
    public  function detail(){
    	
    	admin_role('Task:edit');
    	
    	$referer = '';
    	if(!is_null($_SERVER['HTTP_REFERER'])){
    		$referer = $_SERVER['HTTP_REFERER'];
    	}
    	
    	$get = get(array(
    		array('id','intval',0)
    		
    	));

    	$id = $get['id'];
    	
    	//任务
    	$task = $this->cTask->get_by_task_id($id);

    	$users = $this->cUsers->lists_all();
    	
    	//管理员
    	$admins = $this->cAdmin->lists();
    	
    	//平台
    	$plantforms = $this->cPlantform->lists();
    	 
    	//订单状态
    	$task_status = C('TASK_STATUS');
    	 
    	//支付状态
    	$task_pay_status = C('TASK_PAY_STATUS');
    	
    	//日志
    	$task_logs = $this->cTaskLog->select_by_task_id($id);
    	
    	//添加备注的权限
    	$is_task_log_add = has_role('Task:task_log_add');


        $is_business_admin = 0;
        //判断是否是运维
        if($this->cAdmin->is_group_code('business_man')){
            $is_business_admin = 1;
            //未付款     已付款待确认
            $task_pay_status =  array_slice($task_pay_status,0,2);
        }

        $is_finance = 0;
        //判断是否是财务
        if($this->cAdmin->is_group_code('finance')){
            $is_finance = 1;
            //确认已付款     款已到帐     已退款
            $task_pay_status =  array_slice($task_pay_status,2,3);
        }


    	$this->assign(
    		array(
    			'APP_NAME'			=> APP_NAME,
    			'task'				=> $task,
    			'admins'			=> $admins,
    			'plantforms'		=> $plantforms,
    			'users'				=> $users,
    			'task_status'		=>$task_status,
    			'task_logs'		=> $task_logs,
    			'task_pay_status'	=>$task_pay_status,
    			'referer'			=> $referer,
    			'is_task_log_add'	=> $is_task_log_add,
                'is_business_admin'    => $is_business_admin,
                'is_finance'            => $is_finance,
    			'MainPage'		=> 'Task:detail'
    		)
    	);
    	
    	$this->display(C('ADM_TEMPLATE'));
    }
    
    public function update(){
    	
    	admin_role('Task:edit');
    	    	 
    	
   		$post = post(array(
   			array('task_id'				,'intval',''),
    		
    		//固定不允许修改
   			//array('plantform_id'		,'intval',''),
    		//array('user_id'			,'intval',''),
   				
    		array('activity'			,'trim',''),
    		array('remark'				,'trim',''),
    		array('order_count'			,'intval',''),
    		array('task_order_money'	,'floatval',''),
    		array('commission_money'	,'floatval',''),
    		array('value_added_money'	,'floatval',''),
   			array('pay_status'			,'intval',0),
   			array('task_status'			,'intval',0),
    		array('begin_time'			,'',''),
    		array('end_time'			,'','')
    		
    	));
   	
    	    		
    	$id         = $post['task_id'];
        $pay_status = $post['pay_status'];

    	unset($post['task_id']);
    	
    	//任务
    	$task = $this->cTask->get_by_task_id($id);
    		
    	//要取消任务单
    	if($post['task_status'] == TS_CANCEL){
    		//判断状态
    		
    	  	if(!in_array($task['pay_status'], array(TPS_UNPAY,TPS_REFUND))){
    			json_error('任务单支付状态,必须为：未付款或已退款 ,才能取消');
    		}
    	}
    	
    	
    	//修改了支付状态
    	if($task['pay_status'] != $post['pay_status']){    	
    		if(!has_role('Task:edit_pay_status')){
    			json_error('没有任务单修改支付状态的权限，操作失败');
    		}
    	}

        //支付状态
        $task_pay_status = C('TASK_PAY_STATUS');

        //判断是否是运维
        if($this->cAdmin->is_group_code('business_man')){
            //未付款     已付款待确认
            if(!in_array($pay_status,array_keys(array_slice($task_pay_status,0,2)))){
                json_error('运维只能操作为未付款，已付款待确认，操作失败');
            }
        }

        //判断是否是财务
        if($this->cAdmin->is_group_code('finance')){
            //确认已付款     款已到帐     已退款
            if(!in_array($pay_status,array_keys(array_slice($task_pay_status,2,3)))){
                json_error('财务只能操作为确认已付款，款已到帐，已退款，操作失败');
            }
        }

        $update_result = $this->cTask->update($id,$post);

    	//添加备注
        $post_log = post(array(
    		array('task_id'			,'intval',''),
    		array('message'			,'trim',''),
    		array('admin_id'		,'intval',admin_id_ajax())
    	));
    
    	if(empty($update_result)){
    		if(empty($post_log['message'])){
    			json_error('留言备注不得为空');
    		}
    	}

    	//添加备注
    	$log_result = 0;
    	
    	$task = $this->cTask->get_by_task_id($id);
    	
    	$post_log['task_status']	= $task['task_status'];
    	$post_log['pay_status']		= $task['pay_status'];
    	
    	$log_result = $this->cTaskLog->add($post_log);
	
    	if($update_result || $log_result){
    		
   			$this->cLogs->add('Task:edit','更新任务单成功:'.$id);
    		
    		json_success('保存成功');
    	}else{
    		json_error('保存失败,请确保你对任务单有做修改');
    	}
    }
    
    //批量生成订单
    public function batch_order(){
    	
    	admin_role('Task:add');
    	
    	$get = get(array(
    		array('id'	,'intval',0)
    	));

    	$id 	= $get['id'];
    	    	
    	//任务
    	$task = $this->cTask->get_by_task_id($id);
    	
    	//客户
    	$users = $this->cUsers->lists_all();

    	//管理员
    	$admins = $this->cAdmin->lists();
    	
    	//平台
    	$plantforms = $this->cPlantform->lists();
    	
    	//平台
    	$where 		= array();
    	$page 		= 1;
    	$pageSize 	= PHP_INT_MAX;
    	$allCount	= 0;
    	$orders = $this->cOrder->task_orders($id,$where,$page,$pageSize,$allCount);
    	
    	 
    	//订单状态
    	$task_status = C('TASK_STATUS');
    	 
    	//支付状态
    	$task_pay_status = C('TASK_PAY_STATUS');
    	
    	$this->assign(
    		array(
    			'APP_NAME'			=> APP_NAME,
    			'id'				=> $id,
    			'task'				=> $task,
    			'admins'			=> $admins,
    			'plantforms'		=> $plantforms,
    			'users'				=> $users,
    			'task_status'		=>$task_status,
    			'task_pay_status'	=>$task_pay_status,
    			'orders'			=> $orders,
    			'MainPage'		=> 'Task:batch_order'
    		)
    	);
    	
    	$this->display(C('ADM_TEMPLATE'));
    }
    
	//批量生成订单
    public function batch_order_list(){

    	admin_role('Task:batch_order_list');

    	$get = get(array(
    		array('id'	,'intval',0),
    		array('p'	,'intval',1),
    		array('is_new'	,'intval',0)
    	));

    	$id 		= $get['id'];
        $is_new     = $get['is_new'];

    	//任务
    	$task = $this->cTask->get_by_task_id($id);

    	//判断是否是刷手
		if($this->cAdmin->is_group_code('operator')){
			//是运维，只能看到自己的任务
			$where['order_admin_id'] = admin_id_get();
		}

		$page 		= $get['p'];
    	$pageSize 	= 500;
		$allCount 	= 0;
				
    	//平台
    	$orders = $this->cOrder->task_orders($id,$where,$page,$pageSize,$allCount);

        //设置区分不同颜色
        $orders = $this->cOrder->task_orders_set_background($orders);

    	//日志
    	$task_logs = $this->cTaskLog->select_by_task_id($id);

    	//日志条数
    	$task_logs_count = count($task_logs);
    	
    	//管理员
    	$admins = $this->cAdmin->operator_list();
    	
    	//快递
    	$shippings = $this->cShipping->lists();
    	
		//添加备注的权限
    	$is_task_log_add = has_role('Task:task_log_add');
    	
    	/**
    	 +------------------------------------------------------------------------------
    	 * 分页
    	 +------------------------------------------------------------------------------
    	*/
    	//导入分页类
    	import("@.ORG.Page");
    	
    	$pageParams = array(
    		'g'		=> 'Admin',
    		'id'	=> $id
    	);
    	// 实例化分页类
    	$p = new Page($allCount,$pageSize,$pageParams);
    	
    	// 分页显示输出
    	$pager = $p->show();
    	
    	/**
    	 +------------------------------------------------------------------------------
    	 * 分页
    	 +------------------------------------------------------------------------------
    	 */



        //1.分配帐号
        $is_task_assign_member = has_role('Task:assign_member');

        //2.分配下单URL
        $is_task_assign_url = has_role('Task:assign_url');

        //3.分配收货地址
        $is_task_assign_address = has_role('Task:assign_address');


        //4.分配刷手
        $is_task_assign_order = has_role('Task:assign_order');

        //5.执行完毕
        $is_task_finish = has_role('Task:task_finish');

        //6.收货确认
        $is_task_order_receive = has_role('Task:order_receive');

        //7.重置帐号
        $is_task_reset_member = has_role('Task:reset_member');


        //判断是否是运维
        $main_page = 'Task:batch_order_list';
        if($this->cAdmin->is_group_code('business_man')){
            $main_page = 'Task:batch_order_view';
        }else{
            if($is_new){
                $main_page = 'Task:batch_order_list_new';
            }
        }

        //日期间隔天数
        $day_span   = day_span(full_date(),$task['begin_time']);

    	$this->assign(
    		array(
    			'APP_NAME'			=> APP_NAME,
    			'id'				=> $id,
    			'orders'			=> $orders,
    			'task'				=> $task,
    			'admins'			=> $admins,
    			'task_logs'			=> $task_logs,
    			'task_logs_count'	=> $task_logs_count,

    			'shippings'			=> $shippings,
    			'pager'				=> $pager,
    			'is_task_log_add'	=> $is_task_log_add,
                'is_task_order_receive' => $is_task_order_receive,

                'is_task_assign_member'           => $is_task_assign_member,
                'is_task_assign_url'              => $is_task_assign_url ,
                'is_task_assign_address'          => $is_task_assign_address,
                'is_task_assign_order'            => $is_task_assign_order ,
                'is_task_finish'                  => $is_task_finish ,
                'is_task_order_receive'           => $is_task_order_receive,
                'is_task_reset_member'            => $is_task_reset_member,

                'day_span'              => $day_span,
    			'MainPage'			    => $main_page
    		)
    	);
    	
    	$this->display(C('ADM_TEMPLATE'));
    }
    
    function batch_order_do(){
    
    	import('@.ORG.Order');
	    import('@.ORG.OrderGoods');
	   
	    $post = post(array(
    		
	    	array('goods_url'	,'trim'		,''),
    		array('goods_name'	,'trim'		,''),
    		array('keywords'	,'trim'		,''),
    		array('goods_number','float'	,''),
    		array('goods_price'	,'float'	,''),
    		
    		array('final_price'	,'float'	,''),
    		array('remark'		,'trim'	,''),
    		array('add_count'	,'intval'	,0),
    		
    		array('task_id'		,'intval'	,0)
    	));
    	
    	$task_id	= $post['task_id'];
    	$add_count	= $post['add_count'];
    	
    	//任务
    	$task = $this->cTask->get_by_task_id($task_id);
    	
    	if(!$task){
    		json_error('任务单不存在！');
    	}

    	//验证数量
    	if($add_count <= 0){
    		json_error('生成数量不得小于等于0！');
    	}
    	
    	
    	$order = $post;
    	unset($order['add_count']);
    	
    	//订单列表
    	$orders = array();
    	for ($i = 1;$i <= $add_count;$i++){
    		$orders[] = $order;
    	}


	    //添加订单
	    $add_count =  $this->cTask->add_orders($orders);
	    
	    if($add_count > 0){
	    	json_success('成功添加订单'.$add_count.'个');
	    }else{
	    	json_error('添加订单失败');
	    }
    }
    
    
 	//批量添加
    public function batch_add_do(){
    	
    	admin_role('Task:add');
    	
    	import('@.ORG.Order');
	    import('@.ORG.OrderGoods');
    	import('@.ORG.BatchAdd');
    	import('@.ORG.TaskOrderBatchAdd');
    	

   		$post = post(array(
    		array('task_id'	,'intval',0),
    		array('content'	,'trim','')
    	));

    	$task_id	= $post['task_id'];
    	
    	//任务
    	$task = $this->cTask->get_by_task_id($task_id);
    	
    	if(!$task){
    		json_error('任务单不存在！');
    	}
    	
    	
    	$post['admin_id'] 	= admin_id_ajax();
    	$content			= $post['content'];
    	
    	
    	$cTOBatchAdd = new TaskOrderBatchAdd();
    	$aly_result = $cTOBatchAdd->analyze($content);
    	
    	if($aly_result){
    		//正常
    		$check_rlt = $cTOBatchAdd->format_check();
    		
    		if($check_rlt){
    			//正确
    			
    			//格式化
    			$taskOrders = $cTOBatchAdd->line_format();
    			
    			$add_count = 0;
    			foreach ($taskOrders as $i => $o){
    				//添加入库
    				$taskOrders[$i]['task_id'] = $task_id;
    			}
    			
    			//添加订单
	    		$add_count =  $this->cTask->add_orders($taskOrders);
    			
    			
	    		if($add_count > 0){
			    	json_success('成功添加订单'.$add_count.'个');
			    }else{
			    	json_error('添加订单失败',$cTOBatchAdd->format_errors);
			    }

    		}else{
    			//有错
    			json_error('数据格式检查有错误',$cTOBatchAdd->format_errors);
    		}
  
    	}else{
    		//错误 
    		json_error($cTOBatchAdd->error,$cTOBatchAdd->format_errors);
    	}
    }
    
    //备注
 	public function task_log_add(){
    	
 		admin_role('Task:task_log_add');
 		
   		$post = post(array(
    		array('task_id'			,'intval',''),
    		array('message'			,'trim',''),
    		array('admin_id'		,'intval',admin_id_ajax())
    	));

    	$task_id = $post['task_id'];
    	
    	//任务
    	$task = $this->cTask->get_by_task_id($task_id);
    	
    	$post['task_status']	= $task['task_status'];
    	$post['pay_status']		= $task['pay_status'];
    	
    	$add_result = $this->cTaskLog->add($post);
    		
		if($add_result){		
			json_success('备注添加成功');
		}else{
			json_error('备注添加失败');
		}
    }
    
    //任务订单汇总
    function task_order_summary(){
 		
    	$get = get(array(
    		array('id','intval',0)
    		
    	));

    	$id = $get['id'];

    	//任务
    	$task = $this->cTask->get_by_task_id($id);

    	//汇总订单金额
    	$admin_summary = $this->cOrder->task_summary($id);

        //汇总一下
        $summary = $this->cOrder->summary($admin_summary);

        //判断是否是刷手
        $order_admin_id = 0;
        if($this->cAdmin->is_group_code('operator')){
            //是运维，只能看到自己的任务
            $order_admin_id = admin_id_get();
            foreach($admin_summary as $i => $s){
                if($order_admin_id != $s['order_admin_id']){
                    unset($admin_summary[$i]);
                }
            }
        }

        //是否有刷手查看汇总
        $is_operator_summary = has_role('Task:operator_summary');


        //判断是否是运维
        $is_business_admin = 0;
        if($this->cAdmin->is_group_code('business_man')){
            $is_business_admin = 1;
        }


    	$this->assign(
    		array(
    			'id'				=> $id,
    			'task'				=> $task,
                'admin_summary'		=> $admin_summary,
    			'summary'			=> $summary,
                'is_business_admin' => $is_business_admin,
                'is_operator_summary'=> $is_operator_summary
    		)
    	);
    	
    	$this->display('Task:task_order_summary');   
    }

    //分配帐号
    function assign_member(){

        //分配帐号权限
        admin_role('Task:assign_member');
    	
    	import('@.ORG.Member');
    	
    	$post = post(array(
    		array('id',		'intval'		,0)
    	));
    	
		$task_id = $post['id'];

    	//任务
    	$task = $this->cTask->get_by_task_id($task_id);

    	if(!in_array($task['pay_status'], array(TPS_CONFIRM_PAID,TPS_IN_ACCOUNT))){
    		json_error('确认已付款或款已到帐的的任务才能开始协调,操作失败!');
    	}
    	
    	$where 		= array();
    	$page 		= 1;
    	$pageSize 	= PHP_INT_MAX;
    	$allCount	= 0;
    	
    	//订单
    	$orders = $this->cOrder->task_orders($task_id,$where,$page,$pageSize,$allCount);
    	
    	//平台
    	$plantform_id   = $task['plantform_id'];
        $user_id        = $task['user_id'];

    	//数量
    	$number			= count($orders);
    	
    	    	
    	//获取近n天下过单的会员 
    	$ordered_members = $this->cOrder->recent_days_shop_member_id($user_id);

    	$cMember = new Member();
    	$members = $cMember->get_by_plantform_id($plantform_id,$number,$ordered_members);
    	    	
    	//订单数量
        $order_count = 0;
        foreach ($orders as $o){

            //如果已经有收货人信息，则跳过不分配
            if(empty($o['member_id'])){
                $order_count++;
            }
        }

    	$member_count= count($members);
    	
    	if($order_count > $member_count){
    		//会员数量不足
    		json_error('订单数:'.$order_count.',会员数:'.$member_count.',会员数量不足,请先添加会员数据');	
    	}
    	
    	//乱序
    	shuffle($members);
    	
    	$set_success = 0;
    	//已存在会员数
    	$exist_member = 0;
    	
    	foreach ($orders as $o){
    		
    		//如果已经有收货人信息，则跳过不分配
    		if(!empty($o['member_id'])){
    			$exist_member++;
    			continue;
    		}
    		
    		//取出一个
    		$mbr 		= array_shift($members);
    		$set_aft 	= $this->cOrder->order_set_member($o['order_id'],$mbr['member_id']);
    		
    		if($set_aft > 0){
    			$set_success++;
    		}
    	}
    	
    	if($order_count == $exist_member){
    		json_error($order_count.'个订单已分配会员,忽略跳过');
    	}
    	
    	if($set_success > 0){
    		
    		$this->cLogs->add('Task:assign','任务单:'.$task_id.',分配会员成功');
    		
    		//设置成协调
    		$msg = '';
    		$this->cTask->update_task_status($task_id,TS_SETTLE,$msg);
    		
   			json_success($set_success.'个订单分配会员成功,'.$msg);

    	}else{
    		json_error('分配会员失败');
    	}   	
    }
    
    
  	//分配订单
    function assign_order(){
    	    	    		
    	admin_role('Task:assign_order');
    	
    	$post = post(array(
    		array('task_id',			'intval'	,0),
    		array('check_orders',		'trim'		,''),
	    	array('order_admin_id'		,'intval'	,0)
    	));
    	
    	$task_id 	= $post['task_id'];
    	$orders_id 	= $post['check_orders'];
    	$admin_id 	= $post['order_admin_id'];
    	
    	//任务
    	$task = $this->cTask->get_by_task_id($task_id);
    	    	
    	if(!in_array($task['pay_status'], array(TPS_CONFIRM_PAID,TPS_IN_ACCOUNT))){
    		json_error('确认已付款或款已到帐的的任务才能开始协调,操作失败!');
    	}
    	
    	
    	//任务未开始
    	if($task['task_status'] == TS_UNSTART){
    		//变成协调中
    		$a = $this->cTask->update($task_id, array(
    			'task_status' => TS_SETTLE
    		));
    	}
    	
    	if($admin_id > 0 && $orders_id != ''){
    		$aft_rows = $this->cOrder->assign_order($orders_id,$admin_id);
    		
    		if($aft_rows > 0){
    			
    			//设置成协调
	    		$msg = '';
	    		$this->cTask->update_task_status($task_id,TS_SETTLE,$msg);
    		
    			json_success($aft_rows.'个订单分配成功,'.$msg);
    		}else{
    			json_error('分配订单失败');	
    		}
    	}else{
    		json_error('check_orders,order_admin_id参数错误，请检查');
    	}   	
    }
    
    
    
 	//分配收货地址
    function assign_address(){
    	
    	admin_role('Task:assign_address');
    	
    	import('@.ORG.UserAddress');
    	
    	$post = post(array(
    		array('id',		'intval'		,'id')
    	));
    	
		$task_id = $post['id'];

    	//任务
    	$task = $this->cTask->get_by_task_id($task_id);

    	if(!in_array($task['pay_status'], array(TPS_CONFIRM_PAID,TPS_IN_ACCOUNT))){
    		json_error('确认已付款或款已到帐的的任务才能开始协调,操作失败!');
    	}
    	
    	//订单
    	$orders = $this->cOrder->empty_address_order($task_id);
    	
    	//平台
    	$plantform_id = $task['plantform_id'];
    	
    	//数量
    	$number			= count($orders);
    	
    	$cUAddress = new UserAddress();
    	$address = $cUAddress->get_last_address($number);
    	    	
    	//订单数量
    	$order_count 	= count($orders);
    	$address_count	= count($address);
    	
    	if($order_count > $address_count){
    		//会员数量不足
    		json_error('订单数:'.$order_count.',地址数:'.$address_count.',地址数量不足,请先添加地址数据');	
    	}
    	
    	//乱序
    	shuffle($address);
    	
    	$set_success 	= 0;
    	//原来已有的地址数
    	$exist_address 	= 0;
    	
    	foreach ($orders as $o){
    		
    		//如果已经有收货人信息，则跳过不分配
    		if($o['consignee'] != '' || $o['address'] != '' || $o['mobile_phone'] != ''){
    			$exist_address++;
    			continue;
    		}
    		
    		
    		//取出一个
    		$addr 		= array_shift($address);
    		$set_aft 	= $this->cOrder->order_set_address($o['order_id'],$addr);
    		
    		if($set_aft > 0){
    			$set_success++;
    		}
    	}
    	
    	//都已分配
    	if($order_count == $exist_address){
	    	
    		json_error($order_count.'个订单已分配地址,忽略跳过');
    	}
    	
    	if($set_success > 0){

    		$msg = $set_success.'个订单分配地址成功';
    		if($exist_address > 0){
    			$msg .= ','.$exist_address.'个订单已分配地址,忽略跳过';	
    		}
    		
    	  	//设置成协调
    		$msg = '';
    		$this->cTask->update_task_status($task_id,TS_SETTLE,$msg);
    	
	    	$this->cLogs->add('Task:assign','任务单:'.$task_id.',分配地址成功,'.$msg);
    	
   			json_success($set_success.'个订单，分配地址成功');

    	}else{
    		json_error('分配地址失败');
    	}   	
    }
    
    
 	//分配会员
    function assign_url(){
    	
    	admin_role('Task:assign_url');
    	
    	import('@.ORG.Keywords');
    	    	    	
    	$post = post(array(
    		array('id',		'intval'		,'id')
    	));
    	
		$task_id = $post['id'];

    	//任务
    	$task = $this->cTask->get_by_task_id($task_id);
    	    	
       	if(!in_array($task['pay_status'], array(TPS_CONFIRM_PAID,TPS_IN_ACCOUNT))){
    		json_error('确认已付款或款已到帐的的任务才能开始协调,操作失败!');
    	}
    	
    	//订单
    	$where 		= array();
    	$page 		= 1;
    	$pageSize 	= PHP_INT_MAX;
    	$allCount	= 0;
    	$orders = $this->cOrder->task_orders($task_id,$where,$page,$pageSize,$allCount);
    	
    	//平台
    	$plantform_id = $task['plantform_id'];
    	
    	//数量
    	$number			= count($orders);
    	
    	$cKeywords = new Keywords();
    	$urls = $cKeywords->get_by_plantform_id($plantform_id,$number);
    	
    	
    	//订单数量
    	$order_count = count($orders);
    	$urls_count= count($urls);
    	
    	if($urls_count == 0){
    		//会员数量不足
    		json_error('订单数:'.$order_count.',下单URL数:'.$urls_count.',下单URL数不足,请先添加下单URL');	
    	}
    	    	
    	$set_success = 0;
    	//已存在会员数
    	$exist_url = 0;
    	
    	foreach ($orders as $i=>$o){
    		
    		//如果已经有收货人信息，则跳过不分配
    		if(!empty($o['order_url'])){
    			$exist_url++;
    			continue;
    		}
    		
    		//取余平均分
    		$mod = ($i % $urls_count);
    		
    		
    		//取出一个
    		$u 		= $urls[$mod];
    		$set_aft 	= $this->cOrder->order_set_order_url($o['order_id'],$u);
    		
    		if($set_aft > 0){
    			$set_success++;
    		}
    	}
    	
    	if($order_count == $exist_url){
    		json_error($order_count.'个订单已分配下单URL,忽略跳过');
    	}
    	
    	if($set_success > 0){
    		
    		//设置成协调
	    	$msg = '';
	    	$this->cTask->update_task_status($task_id,TS_SETTLE,$msg);
    		
	    		
    		$this->cLogs->add('Task:assign','任务单:'.$task_id.',分配URL成功,'.$msg);
    		
   			json_success($set_success.'个订单分配下单URL成功');

    	}else{
    		json_error('分配下单URL失败');
    	}   	
    }
    
    
    /**
     * 
     * 导出csv
     */
    function export_csv(){
    
    	admin_role('Task:export_csv');
    	
    	
       $get = get(array(    		
    		array('id'		,'intval'	,0)
    	));
    	
    	$task_id = $get['id'];
    	
    	//任务
    	$task = $this->cTask->get_by_task_id($task_id);
    	
    	$file_name = '任务单'.$task_id.'-'.$task['plantform_name'].'-'.$task['shop_name'].'.csv';
    	
    	//导出详细内容,权限
    	$is_export_csv_pro = has_role('Task:export_csv_pro');
    	
    	//导出的订单
    	if($is_export_csv_pro){

            //刷手
            $is_operator 	= $this->cAdmin->is_group_code('operator');
            $order_admin_id = 0;
            if($is_operator){
                $order_admin_id = admin_id_get();
            }

    		$data = $this->cOrder->export_orders_pro($task_id,$order_admin_id);
    	}else{
    		$data = $this->cOrder->export_orders($task_id);
    	}
    	
    	export_csv($data,$file_name);
    }
    
    
    function task_log(){
    
    	admin_role('Task:index');
    	
    	$get = get(array(
            array('id'		,'intval'	,0),
            array('remark'	,'intval'	,0)

    	));
    	
    	$id = $get['id'];
        $remark= $get['remark'];
    	
    	//日志
    	$task_logs = $this->cTaskLog->select_by_task_id($id);
    	
    	
 		$this->assign(
    		array(
    			'task_logs'	=> $task_logs,
                'remark'    => $remark,
                'task_id'   => $id
    		)
    	);
    	
    	$this->display('Task:task_log');
    	   
    	
    }


    /**
     * 修改订单备注
     */
    function order_remark(){

        admin_role('Task:index');

        $get = get(array(
            array('order_id'		,'intval'	,0)
        ));

        $order_id = $get['order_id'];

        //日志
        $order = $this->cOrder->get_by_id($order_id);

        $this->assign(
            array(
                'order'	=> $order,
            )
        );

        $this->display('Task:order_remark');

    }

    /**
     * 修改订单备注
     */
    function order_remark_update(){

        admin_role('Task:index');

        $post = post(array(
            array('order_id'   ,'intval'	,0),
            array('remark'	    ,'trim'	    ,'')
        ));

        $order_id   = $post['order_id'];
        $remark     = $post['remark'];

        $upItems = array(
            'remark' => $remark
        );

        //日志
        $up_aft = $this->cOrder->update($order_id,$upItems);

        if($up_aft){
            json_success('备注保存成功');
        }else{
            json_success('备注保存失败或未修改');
        }
    }


    /**
     * 
     * 设置为已完成
     */
    function set_finish(){
    
    	admin_role('Task:task_finish');
    	
    	$post = post(array(    		
    		array('task_id'		,'intval'	,0),
    		
    	));

    	$task_id = $post['task_id'];

    	
    	//协调和总管理才能执行完毕
		$is_super_admin = $this->cAdmin->is_group_code('super_admin');
		$is_coordinator = $this->cAdmin->is_group_code('coordinator');
		
		$can_task_finished = 0;
		if(!($is_super_admin || $is_coordinator)){
			json_error('协调员和超级管理员才能执行完毕');
		}
		
	
    	//任务
    	$task = $this->cTask->get_by_task_id($task_id);
    	
    	if($task['task_status'] == TS_RUNNING){
    		//如果等于执行中才能完毕
    		//设置成执行中
    		$msg = '';
    		$up_result = $this->cTask->update_task_status($task_id,TS_FINISH,$msg);

    		if($up_result){
    			json_success($msg);
    		}else{
    			json_error($msg);
    		}
    		
    	}else{
    		json_error('执行中的任务才能执行完毕');
    	}
    }
    
    
   /**
     * 
     * 设置帐号
     */
   function reset_member_id(){
    
		admin_role('Task:reset_member');
    	
    	$post = post(array(
    		array('check_orders',		'trim'		,'')
    	));
    	
    	$orders_id 	= $post['check_orders'];
    	    	
    	if($orders_id != ''){
    		$aft_rows = $this->cOrder->reset_member_id($orders_id);
    		
    		if($aft_rows > 0){
    			
    			json_success($aft_rows.'个订单重置帐号成功,');
    		}else{
    			json_error('重置帐号失败');	
    		}
    	}else{
    		json_error('check_orders参数错误，请检查');
    	}   	
   }


    /**
     *
     * 提交等待收货确认订单
     */
    function receive_status_reset(){

        admin_role('Task:order_receive');

        $post = post(array(
            array('check_orders',		'trim'		,'')
        ));

        $orders_id 	= $post['check_orders'];

        if($orders_id != ''){
            $aft_rows = $this->cOrder->receive_status_reset($orders_id);

            if($aft_rows > 0){
                json_success($aft_rows.'个订单重置为:"未收货" 成功');
            }else{
                json_error('没有被重置的订单，已排除"未收货，已收货"订单');
            }
        }else{
            json_error('check_orders参数错误，请检查');
        }
    }


    /**
     *
     * 提交等待收货确认订单
     */
    function receive_submit_orders(){

        admin_role('Task:order_receive');

        $post = post(array(
            array('check_orders',		'trim'		,'')
        ));

        $orders_id 	= $post['check_orders'];

        if($orders_id != ''){
            $aft_rows = $this->cOrder->receive_submit_orders($orders_id);

            if($aft_rows > 0){
                json_success($aft_rows.'个订单提交成功，等待收货确认操作');
            }else{
                json_error('没有订单被提交，已排除"已收货"订单');
            }
        }else{
            json_error('check_orders参数错误，请检查');
        }
    }

    /**
     * 查看详情
     */
    function receive_details(){

        admin_role('Task:order_receive');

        $get = get(array(
            array('order_id',		'intval'	,0),
            array('type',		    'trim'		,'')
        ));

        $order_id   = $get['order_id'];
        $type       = $get['type'];

        if(in_array($type,array('proxy_content','sid_content','orders_content','confirm_content'))){
            $order = $this->cOrder->get_by_id($order_id);

            header("Content-type: text/html; charset=utf-8");
            echo $order[$type];
            exit;
        }
    }


    /**
     * 店铺分隔的订单列表
     */
    function shop_order_list(){

        admin_role('Task:batch_order_list');

        $get = get(array(
            array('begin_time'			,''	,short_date()),
            array('end_time'			,''	,short_date())
        ));

        //开始时间
        $begin_time	= $get['begin_time'];
        //结束时间
        $end_time	= $get['end_time'];

        //管理员
        $order_admin_id = admin_id_get();

        //1.任务订单
        $task_orders = $this->cOrder->get_top_orders_by_admin_id($order_admin_id,$begin_time,$end_time);

        //2.刷单汇总
        $summary = $this->cOrder->get_order_summary_by_admin_id($order_admin_id,$begin_time,$end_time);

        //我的订单总量
        $order_count  = $summary['order_count'];
        //完成量
        $finish_count = $summary['finish_count'];

        //完成百分比
        $percent = 0;
        if($order_count > 0){
            $percent = round(floatval((int)$finish_count / (int)$order_count) * 100,2);
        }

        $this->assign(
            array(
                'begin_time'            => $begin_time,
                'end_time'              => $end_time,
                'task_orders'           => $task_orders,
                'percent'               => $percent,
                'order_count'           => $order_count,
                'finish_count'          => $finish_count,
                'MainPage'			    => 'Task:shop_order_list'
            )
        );

        $this->display(C('ADM_TEMPLATE'));

    }
}